package com.ben.multiple.shiro;

import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

public class Base {
    public static final String GLOBAL_URL_PREFIX = "http://localhost:9019";
    public static final String ACCESS_TOKEN = "087ac6f4-6b42-4a4b-9256-a9b4c6a38d511";
//    public static final String ACCESS_TOKEN = "";
    public static final String ACCESS_TOKEN_KEY = "token";
    protected static TestRestTemplate restTemplate = new TestRestTemplate(new RestTemplateBuilder());

    @Test
    void login() {
        String username = "a";
        String password = "a";
        String url = GLOBAL_URL_PREFIX + "/login";
        Map<String, Object> body = new HashMap<>();
        body.put("username", username);
        body.put("password", password);
        HttpEntity<Object> httpEntity = this.getHttpEntity(body);
        ResponseEntity<String> entity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        this.print(entity);
    }

    @Test
    void admin() {
        String url = GLOBAL_URL_PREFIX + "/admin";
        HttpEntity<Object> httpEntity = this.getHttpEntity();
        ResponseEntity<String> entity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
        this.print(entity);
    }
    @Test
    void index() {
        String url = GLOBAL_URL_PREFIX + "/index";
        HttpEntity<Object> httpEntity = this.getHttpEntity();
        ResponseEntity<String> entity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
        this.print(entity);
    }
    @Test
    void add() {
        String url = GLOBAL_URL_PREFIX + "/add";
        HttpEntity<Object> httpEntity = this.getHttpEntity();
        ResponseEntity<String> entity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
        this.print(entity);
    }

    protected <T> HttpEntity<T> getHttpEntity() {
        HttpHeaders headers = new HttpHeaders();
        headers.add(ACCESS_TOKEN_KEY, ACCESS_TOKEN);
        return new HttpEntity<>(headers);
    }

    protected <T> HttpEntity<T> getHttpEntity(T t) {
        HttpHeaders headers = new HttpHeaders();
        headers.add(ACCESS_TOKEN_KEY, ACCESS_TOKEN);
        return new HttpEntity<>(t, headers);
    }

    protected void print(ResponseEntity<?> entity) {
        if (entity == null || HttpStatus.OK != entity.getStatusCode()) {
            System.out.println(entity);
            return;
        }
        System.out.println(entity.getBody());
    }

}
